//
//  ANInputQuantity.m
//  Ants
//
//  Created by ZHM on 16/9/12.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANInputQuantity.h"

@interface ANInputQuantity ()

@property (nonatomic, weak) UIButton *coverView;
@property (nonatomic, assign) NSInteger lastLength;

@end

@implementation ANInputQuantity

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addUpAllChildView];
        self.userInteractionEnabled = YES;
        self.backgroundColor = ANToopColor;
        _lastLength = 0;
    }
    return self;
}

+ (instancetype)showInputQuantityAtViewController: (id)delegate{
    //输入视图
    ANInputQuantity *inputPriceView = [[ANInputQuantity alloc] initWithFrame:CGRectMake(0, ANKeyWindow.height, ANKeyWindow.width, 44)];
    inputPriceView.quantityField.delegate = delegate;
    inputPriceView.delegate = delegate;
    
    //蒙版视图
    UIButton *coverView = [[UIButton alloc] initWithFrame:[UIScreen mainScreen].bounds];
    coverView.backgroundColor = [UIColor blackColor];
    coverView.alpha = 0;
    [coverView addTarget:inputPriceView action:@selector(clickCoverView) forControlEvents:UIControlEventTouchUpInside];
    inputPriceView.coverView = coverView;
    [ANKeyWindow addSubview:coverView];
    
    [ANKeyWindow addSubview:inputPriceView];
    
    //监听键盘的弹出
    [[NSNotificationCenter defaultCenter] addObserver:inputPriceView selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [UIView animateWithDuration:0.25 animations:^{
        coverView.alpha = 0.5;
    }];
    
    //弹出键盘
    [inputPriceView.quantityField becomeFirstResponder];
    return inputPriceView;
}
#pragma mark -- 键盘Frame改变时候调用
- (void)keyboardFrameChange:(NSNotification *)notification {
    //NSLog(@"%@",notification.userInfo);
    //获取键盘动画时间
    CGFloat time = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //获取键盘Frame
    CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //NSLog(@"%@",NSStringFromCGRect(frame));
    if (frame.origin.y == ANKeyWindow.height) {
        [UIView animateWithDuration:time animations:^{
            //还原
            self.transform = CGAffineTransformIdentity;
        }];
    } else {
        [UIView animateWithDuration:time animations:^{
            //移动
            self.transform = CGAffineTransformMakeTranslation(0, -frame.size.height - 44);
        }];
    }
}
//取消选项视图
- (void)clickCoverView {
    [self hiddenInputQuantity];
    if ([self.delegate respondsToSelector:@selector(hiddenInputQuantity:)]) {
        [self.delegate hiddenInputQuantity:self];
    }
}
- (void)hiddenInputQuantity {
    [self reloadPriceView];
    [self hiddenCoverView];
}
- (void)reloadPriceView {
    if (self.quantityField.text.length == 0) {
        self.quantityField.text = @"0";
    }
}
- (void)hiddenCoverView {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.coverView.alpha = 0;
        [weakSelf removeFromSuperview];
    } completion:^(BOOL finished) {
        [weakSelf.coverView removeFromSuperview];
    }];
}
- (void)addUpAllChildView  {
    CGFloat label_Max_W = 70;
    CGFloat field_H = 25;
    CGFloat field_Y = (self.height - field_H) / 2;
    CGFloat margin = 10;
    
    UILabel *priceLabel = [[UILabel alloc] init];
    priceLabel.text = @"数量:";
    //priceLabel.font = [UIFont systemFontOfSize:<#(CGFloat)#>];
    CGSize priceLabelSize = [priceLabel.text sizeOfTextWithMaxSize:CGSizeMake(label_Max_W, MAXFLOAT) font:priceLabel.font];
    CGFloat Y = (self.height - priceLabelSize.height) / 2;
    priceLabel.frame = (CGRect){{margin,Y},priceLabelSize};
    [self addSubview:priceLabel];
    
    UITextField *quantityField = [[UITextField alloc] init];
    quantityField.placeholder = @"0";
    CGFloat priceField_X = CGRectGetMaxX(priceLabel.frame) + margin;
    quantityField.frame = CGRectMake(priceField_X, field_Y, self.width *0.67 - priceField_X - margin, field_H);
    quantityField.keyboardType = UIKeyboardTypeDecimalPad;
    quantityField.returnKeyType = UIReturnKeyDone;
    quantityField.backgroundColor = [UIColor whiteColor];
    quantityField.layer.cornerRadius = 3.0;
    _quantityField = quantityField;
    [self addSubview:quantityField];
    
    [quantityField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldDidChange:(UITextField *)textField {
    if (textField.text.length == 0) {
        _lastLength = 0;
        return;
    }
    //一次输入1个字符以上的删除
    if (textField.text.length >= _lastLength + 2) {
        ANLog(@"输入错误 有可能是多汉字");
        textField.text = [textField.text substringToIndex:textField.text.length - (textField.text.length - _lastLength)];
        _lastLength = textField.text.length;
        ANLog(@"结果:%@ -- 长度:%ld",textField.text,(long)_lastLength);
        return;
    }
    unichar single = [textField.text characterAtIndex:textField.text.length - 1];
    if (!(single >='0' && single<='9')) {
        ANLog(@"亲，您输入的格式不正确");
        textField.text = [textField.text substringToIndex:textField.text.length - 1];
    }else {
        //首字母不能为0
        if([textField.text length] == 1){
            if(single == '0'){
                ANLog(@"亲，第一个数字不能为'0'");
                textField.text = @"";
            }
        }
    }
    if (textField.text.length > 3) {
        textField.text = [textField.text substringToIndex:3];
    }
    _lastLength = textField.text.length;
    
}
- (void)dealloc {
    ANLog(@"界面消失:%s",__func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
